import { forwardRef, Inject, Injectable } from '@nestjs/common'
import { JwtService } from '@nestjs/jwt'
import { LoginUserDto } from '../user/dto/login-user.dto'
import { UserService } from '../user/user.service'
import { ResultFormat } from '../../format/ResultFormat'

@Injectable()
export class AuthService {
  constructor(
    @Inject(forwardRef(() => UserService))
    private readonly userService: UserService,
    private readonly jwtService: JwtService
  ) {}

  async validateUser(loginUserDto: LoginUserDto): Promise<any> {
    const user = this.userService.findOne(loginUserDto)
    if (user) {
      return user
    }

    return null
  }

  async login(user: any): Promise<any> {
    if (!user.success) {
      return new ResultFormat(0, null, false, '账号或密码错误')
    }
    const payload = {
      id: user.rows.id,
      nickName: user.rows.nickName,
      loginEmail: user.rows.loginEmail,
      photoUrl: user.rows.photoUrl
    }
    const result =  {
      token: this.jwtService.sign(payload),
      ...payload
    }
    return new ResultFormat(0, result, true, '操作成功')
  }
}
